package com.liuheng.manager.interceptor;

import com.alibaba.fastjson2.JSON;
import com.liuheng.spzx.model.entity.system.SysUser;
import com.liuheng.spzx.model.vo.common.Result;
import com.liuheng.spzx.model.vo.common.ResultCodeEnum;
import com.liuheng.util.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if("OPTIONS".equals(method)){
            return true;//放行
        }
        String token = request.getHeader("token");
        SysUser user= (SysUser) redisTemplate.opsForValue().get("user:login" + token);
        if(user!=null){
            AuthContextUtil.setUser(user);
            redisTemplate.expire("user:login" + token,30, TimeUnit.MINUTES);
            return true;
        }
        responseNoLoginInfo(response);
        return false;
    }

    private void responseNoLoginInfo(HttpServletResponse response) {
        Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer=null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer=response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();
    }
}
